package xyz.syyrjx.blog.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import xyz.syyrjx.blog.entity.ticTacToe.Gamer;
import xyz.syyrjx.blog.entity.ticTacToe.Room;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2024/4/25 20:19
 * @description ...
 * @since v0.0.1
 */
@Component
@ServerEndpoint("/ticTacToeWebsocket/{id}")
public class TicTacToeWebSocket {

    private final Logger logger = LoggerFactory.getLogger(AiWebsocketService.class);

    private Session session;
    private String id;

    //存放所有的websocket连接
    private static Map<String,TicTacToeWebSocket> ticTacToeWebSocketServicesMap = new ConcurrentHashMap<>();
    private static List<String> exitGammerList = new CopyOnWriteArrayList<>();

    //建立websocket连接时自动调用
    @OnOpen
    public void onOpen(Session session,@PathParam("id") String id){
        this.session = session;
        this.id = id;
        ticTacToeWebSocketServicesMap.put(id, this);
        logger.debug("有新的websocket连接进入，当前连接总数为" + ticTacToeWebSocketServicesMap.size());
    }

    //关闭websocket连接时自动调用
    @OnClose
    public void onClose(){
        ticTacToeWebSocketServicesMap.remove(this.id);
        Room room = Room.getRoomByGamer(this.id);
        Gamer other = room.getOther(this.id);
        if (exitGammerList.contains(other.getId())){
            Room.removeRoom(room.getId());
        }else {
            exitGammerList.add(other.getId());
        }
        logger.debug("连接断开，当前连接总数为" + ticTacToeWebSocketServicesMap.size());
    }

    //websocket接收到消息时自动调用
    @OnMessage
    public void onMessage(String message){
        logger.debug("this：" + message);
    }

    //通过websocket发送消息
    public void sendMessage(String message, String id){
        TicTacToeWebSocket ticTacToeWebSocket = ticTacToeWebSocketServicesMap.get(id);
        if (ticTacToeWebSocket == null) {
            return;
        }
        try {
            ticTacToeWebSocket.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            logger.debug(this + "发送消息错误:" + e.getClass() + ":" + e.getMessage());
        }
    }
}
